from django.shortcuts import render, HttpResponse

# Create your views here.
import random

from utils.tencent.sms import send_sms_single
from django.conf import settings

from django import forms
from app01 import models

from django.core.validators import RegexValidator


def send_sms(request):
    """ 发送短信
     根据类型使⽤不同的模版
     ?tpl=login -> 1868403
     ?tpl=register -> 1868402
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)
    res = send_sms_single('13971315021', template_id, [code])
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    # 添加正则表达式的校验
    mobile_phone = forms.CharField(label='⼿机号',
                                   validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '⼿机号格式错误'), ])
    # 第⼀个参数为正则表达式 ，第⼆个参数为报错信息
    # 修改密码的默认显示
    password = forms.CharField(
        label='密码',
        # 密码框需要显示为密码类型
        widget=forms.PasswordInput(attrs={'class': 'form-control'})
    )

    # 在数据库中不需要保存确认密码字段，需要⾃定义字段信息
    confirm_password = forms.CharField(
        label='重复密码',
        widget=forms.PasswordInput())

    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        # ⽣成所有字段
        # fields = "__all__"
        # 选择要⽣成表单的字段和顺序
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register(request):
    # 创建表单对象
    """
        用户信息注册
    :param request:
    :return:
    """
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})
